package fr.imag.m2pgi.m2m.geoloc.mqtt.publisher;

import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.HashMap;

import org.fusesource.mqtt.client.BlockingConnection;
import org.fusesource.mqtt.client.Callback;
import org.fusesource.mqtt.client.CallbackConnection;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.Message;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.codec.MessageSupport.AckBase;

/*import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
*/
public class Publisher implements PublishService {

  MQTT client;
  CallbackConnection connection;

  Publisher(String server, int port) throws URISyntaxException {
    MQTT client = new MQTT();
    client.setHost(server, port);
    connection = client.callbackConnection();
    connection.connect(new Callback<Void>() {

      public void onSuccess(Void arg0) {
        System.out.println("Publisher connected");
      }

      public void onFailure(Throwable arg0) {
        arg0.printStackTrace();
      }
    });
  }


  public void sendMessage(Integer z, HashMap<Double, Integer> data) {
    System.out.println("Sending a message...");
    // Format the message
    final ByteBuffer buffer = ByteBuffer.allocate(4+12*data.size());
    buffer.putInt(z);
    for(Double d : data.keySet()) {
      buffer.putDouble(d);
      buffer.putInt(data.get(d));
    }
   
//    final String msg = z.toString()+":"+angle.toString()+":"+distance.toString();
    connection.getDispatchQueue().execute(new Runnable() {
      public void run() {
        System.out.println("Run...");
        connection.publish("/geoloc", buffer.array(), QoS.AT_LEAST_ONCE, false, 
            new Callback<Void>() {
          
          public void onSuccess(Void arg0) {
            System.out.println("Message sent success");
          }

          public void onFailure(Throwable arg0) {
            arg0.printStackTrace();
          }
        });
      }
    });
  }

  public void disconnect() {
    connection.disconnect(new Callback<Void>() {

      public void onSuccess(Void arg0) {
      }

      public void onFailure(Throwable arg0) {
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        connection.disconnect(null);
      }
    });
  }
}
